package com.interceptor;

import com.model.Const;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;

public class AuthorityInterceptor extends HandlerInterceptorAdapter {
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object arg2) throws Exception {
		HttpSession session =request.getSession();
		String path = request.getServletPath();
		Integer gid=(Integer) session.getAttribute(Const.SESSION_GID);
		if (path.matches(Const.NO_INTERCEPTOR_PATH)) {
			return true;
		} else if(gid==1){
			return true;
		}else{
			  String method=request.getRequestURI().substring(request.getContextPath().length() + 1);
			  String authorityName=(String) session.getAttribute(Const.SESSION_AUTHORITY);
              String[] authorityNames=authorityName.split(",");
			if (authorityNames != null) {
				if (Arrays.asList(authorityNames).contains(method)) {
					return true;
				} else {
					response.getWriter().print("<script type='text/javascript'>alert('没有权限');window.history.back();</script>");
					return false;
				}
			}
		}
       return true;
	}
}
